/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:45
 */

package com.lenovo.mso2o.ui.fragment;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMError;
import com.easemob.util.PathUtil;
import com.easemob.util.VoiceRecorder;
import com.lenovo.framework.base.BaseDialogFragment;
import com.lenovo.framework.base.FBaseActivity;
import com.lenovo.framework.util.DLog;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.util.CommonUtil;


/**
 * Created by lit on 2015/11/26.
 */
public class TalkbackDialogFragment extends BaseDialogFragment {
    private TextView tvPressToTalk;
    private ImageView ivPressToTalkVoice;
    private int height;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_NoActionBar);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = inflater.inflate(R.layout.talk_back_dialogfragment, container);
        tvPressToTalk = (TextView) view.findViewById(R.id.tv_press_to_talk);
        LinearLayout pressToTalkLayout = (LinearLayout) view.findViewById(R.id.press_to_talk_layout);
        ivPressToTalkVoice = (ImageView) view.findViewById(R.id.iv_press_to_talk_voice);
        ivPressToTalkVoice.setOnTouchListener(new VoicePressedLintenner());
        ImageView ivVoiceArrows = (ImageView) view.findViewById(R.id.iv_voice_arrows);
        ivVoiceArrows.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
//        showTalkBackAnimation();
//        height = getLayoutHeight(pressToTalkLayout);
//        Rect outRect = new Rect();
//        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
//        final int outHeight = outRect.top;
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
//                        int downY = (int) event.getY() + outHeight * 2;
                        int downY = (int) event.getY();
                        if (isOutDistrict(downY, v)) {
                            dismiss();
                        }
                        break;
                }
                return false;
            }
        });
        return view;
    }

    private void showTalkBackAnimation() {

        ivPressToTalkVoice.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        tvPressToTalk.setText("正在录音");
                        ScaleAnimation animationDown = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f,
                                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDown.setDuration(200);
                        animationDown.setFillAfter(true);
                        animationDown.start();
                        ivPressToTalkVoice.setAnimation(animationDown);
                        break;
                    case MotionEvent.ACTION_UP:
                        tvPressToTalk.setText("按住对讲");
                        ivPressToTalkVoice.clearAnimation();
                        ScaleAnimation animationUp = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f,
                                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationUp.setDuration(200);
                        animationUp.setFillAfter(true);
                        animationUp.start();
                        ivPressToTalkVoice.setAnimation(animationUp);
                        break;
                }
                return true;
            }
        });
    }

    /**
     * 内部类监听语音菜单操作
     */
    class VoicePressedLintenner implements View.OnTouchListener {
        //        private Context context;
        private PowerManager.WakeLock wakeLock;
        private VoiceRecorder recorder;
        private String toChatUsername;
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };

        public VoicePressedLintenner() {
//            this.context = cxt;
            wakeLock = ((PowerManager) (getActivity().getSystemService(Context.POWER_SERVICE))).newWakeLock(
                    PowerManager.SCREEN_DIM_WAKE_LOCK, "mvs");
            recorder = new VoiceRecorder(handler);
        }

        @Override
        public boolean onTouch(final View v, final MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    if (!CommonUtil.checkSDCARD()) {
                        String st4 = getString(R.string.Send_voice_need_sdcard_support);
                        Toast.makeText(getActivity(), st4, Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    ((FBaseActivity) getActivity()).requestPermission(Manifest.permission.RECORD_AUDIO, new Runnable() {
                        @Override
                        public void run() {
                            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                                    == PackageManager.PERMISSION_DENIED) {
                                //((FBaseActivity) getActivity()).showShortToast(R.string.allow_permission_request);
                            } else {
                                try {
                                    v.setPressed(true);
                                    wakeLock.acquire();
                                    toChatUsername = "jk";
                                    //按键效果
                                    tvPressToTalk.setText("正在录音");
                                    ScaleAnimation animationDown = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f,
                                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                                    animationDown.setDuration(200);
                                    animationDown.setFillAfter(true);
                                    animationDown.start();
                                    ivPressToTalkVoice.setAnimation(animationDown);

                                    PathUtil.getInstance().initDirs(null, null, getContext());
                                    recorder.startRecording(null, toChatUsername, getActivity().getApplicationContext());
                                } catch (Exception e) {
                                    DLog.p(e);
                                    v.setPressed(false);
                                    if (wakeLock.isHeld())
                                        wakeLock.release();
                                    if (recorder != null) {
                                        recorder.discardRecording();
                                        recorder.stopRecoding();
                                    }
//                    recordingContainer.setVisibility(View.INVISIBLE);
                                    Toast.makeText(getActivity(), R.string.recoding_fail, Toast.LENGTH_SHORT).show();
                                }

                            }
                        }
                    });
                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (event.getY() < 0) {
                        tvPressToTalk.setText("松开确定取消录音");
                    } else {
                        tvPressToTalk.setText("向上滑动取消录音");
                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    //按键效果
                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                                    == PackageManager.PERMISSION_GRANTED) {
                        //((FBaseActivity) getActivity()).showShortToast(R.string.allow_permission_request);
                        tvPressToTalk.setText("按住对讲");
                        ivPressToTalkVoice.clearAnimation();
                        ScaleAnimation animationUp = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f,
                                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationUp.setDuration(200);
                        animationUp.setFillAfter(true);
                        animationUp.start();
                        ivPressToTalkVoice.setAnimation(animationUp);


                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (event.getY() < 0) {
                            // discard the recorded audio.
                            recorder.discardRecording();
                        } else {
                            // stop recording and send voice file
                            String st1 = getResources().getString(R.string.Recording_without_permission);
                            String st2 = getResources().getString(R.string.The_recording_time_is_too_short);
                            String st3 = "录音失败";
                            try {
                                int length = recorder.stopRecoding();
                                if (length > 0) {
                                    String voicePath = recorder.getVoiceFilePath();
                                    DLog.e("msg", voicePath);
                                    Bundle bundle = new Bundle();
                                    bundle.putString(MSConstants.AUDIO_PATH, voicePath);
                                    mInterface.onRetrieveDialogFragmentData(bundle, MSConstants.FragmentType.DIALOG_TALK_FRAGMENT);
                                    getDialog().dismiss();
                                } else if (length == EMError.INVALID_FILE) {
                                    Toast.makeText(getActivity().getApplicationContext(), st1, Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getActivity().getApplicationContext(), st2, Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(getActivity(), st3, Toast.LENGTH_SHORT).show();
                            }
                        }
                    };
                    return true;
                default:
//                recordingContainer.setVisibility(View.INVISIBLE);
                    ((FBaseActivity) getActivity()).requestPermission(Manifest.permission.RECORD_AUDIO, new Runnable() {
                        @Override
                        public void run() {
                            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)
                                    != PackageManager.PERMISSION_GRANTED) {
                                //((FBaseActivity) getActivity()).showShortToast(R.string.allow_permission_request);
                            } else {
                                if (recorder != null)
                                    recorder.discardRecording();
                            }
                        }
                    });
                    return false;
            }
        }

//    public int getLayoutHeight(View contentRelative) {
//        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
//        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
//        contentRelative.measure(w, h);
//        int height = contentRelative.getMeasuredHeight();
//        Rect outRect = new Rect();
//        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
//        return outRect.height() - height;
//    }
    }
}
